
package com.dream.utils.email;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dream.utils.log.DreamLogUtils;
import com.google.common.collect.Lists;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2012/09/01
 */

@Service("MailJobService")
public class MailJobServiceImpl implements MailJobService {
	
	@Resource(name="threadPoolTaskExecutor")
	private Executor executor;
	
	@Autowired
	private MailCenterService mailCenterService;
	
	@Transactional
	public MailSendingResult sendMail(EMailBean mail,MailServerType type) {
		
		MailSendingResult res = MailSendingResult.FAIL;
		MailSendingTask task = new MailSendingTask();
		task.setMail(mail);
		task.setType(type);
		task.setMailCenterService(mailCenterService);
		
		FutureTask<MailSendingResult> future = new FutureTask<MailSendingResult>(task);  
		executor.execute(future);
		
		try {
			res =  future.get();
		} catch (InterruptedException e) {
			DreamLogUtils.error(this,"sendMail","send mail error",e);
			e.printStackTrace();
		} catch (ExecutionException e) {
			DreamLogUtils.error(this,"sendMail","send mail error",e);
			e.printStackTrace();
		}
		
		return res;
	}
	
	@Transactional
	public List<MailSendingResult> sendBatchMail(List<EMailBean> mails,MailServerType type) {
		
		List<MailSendingResult> results = Lists.newArrayList();;
		List<Future<MailSendingResult>> futures = Lists.newArrayList();
		
		for(EMailBean mail : mails){
			
			MailSendingTask task = new MailSendingTask();
			task.setMail(mail);
			task.setType(type);
			task.setMailCenterService(mailCenterService);
			
			FutureTask<MailSendingResult> future = new FutureTask<MailSendingResult>(task);
			futures.add(future);
			executor.execute(future);
		}
		
		try {
			for(Future<MailSendingResult> f : futures){
				results.add(f.get());
			}
		} catch (InterruptedException e) {
			DreamLogUtils.error(this,"sendBatchMail","send mail error",e);
			e.printStackTrace();
		} catch (ExecutionException e) {
			DreamLogUtils.error(this,"sendBatchMail","send mail error",e);
			e.printStackTrace();
		}
		
		return results;
	}

}
